// pages/pintuan/pintuan.js
let app = getApp();
import util from '../../../utils/util.js';
import WxParse from '../../../libs/wxParse/wxParse.js';
Page({
  /**
   * 页面的初始数据
   type:三人拼 three  -  人人拼 people
   three_pin_xiang:三人拼团详情带悬浮 
   three_pin_yifa: 三人拼团详情带悬浮-拼团已发起
   three_model:三人拼团详情-活动过期
   shareThree:转发后新用户看到详情
   */
  data: {
    type:'people',
    three_pin_xiang: true,
    three_pin_yifa: false,
    three_model: false,
    shareThree: false,
    product:{},
    goods: {},
    gallery: [],
    specificationList: [],
    productList: [],
    userHasCollect: false,
    List_CanT:[],
    List_mmbhr:[],
    Num_mmbhr:100,
    arr_cantuan3:[],
    setInter:''
  },
//生命周期函数--监听页面加载
  onLoad: function (options) {

    let goodsType = options.type//产品类型 -三人拼 -人人拼
    let goodsId = options.id//产品标识产品id
    let shareM = options.shareM || 'shareNot'
    //3人拼团中的 团id
    let pid = options.pid || 0;    
    console.log(goodsType, goodsId, shareM, pid) 
    this.setData({
      'pid':pid,
      'id':goodsId,
      'type':goodsType
    })
    //非主动
    this.pageStatus(goodsType, goodsId, shareM, pid)//页面状态判定 
    this.setNavTitle(goodsType) //设置页面NavigationBarTitle
    this.getmeBackImg()
    this.getPinInfo(goodsId) //得到产品信息
    this.getProductInfo() // 产品详情
    //非主动 END
  },
  //等到当前 pid
  getpidNow() {
    let self = this
    let token = wx.getStorageSync('token') || '';
    wx.request({
      url: util.apiUrl + 'xcx.pin.userpindata_pid',
      data: {
        'goods_id': self.data.id
      },
      header: {
        'content-type': 'application/json',
        'X-ECAPI-Authorization': token
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        let pidNow = res.data.pid
        self.setData({
          'pidNow': pidNow
        })
      }
    })
  },

  getmeBackImg() {
    let self = this
    util.request(util.apiUrl + 'xcx.pin.banner', 'POST', {
      id: [117]
    }).then(res => {
      console.log('getmeBackImg', res.data[117])
    }).catch(err => {
      console.log(err)
      let arr = err.data[117]
      if (arr.length > 0) {
        self.setData({
          'me_back': arr
        })
      }
    });
  },

//页面状态判定 
  pageStatus(goodsType, goodsId, shareM, pid) {
    let self = this
    if(goodsType != 'people'){
      goodsType = 'three'
    }

    if (shareM == 'shareNot') {
      //不是分享
      if (goodsType == 'three') {
        self.getList_CanT(goodsId)//三人拼 —— 参团列表 - 显示
        //判断三人团是不是拼主已经拼团。status_yifa  true->已经拼团  false->没有拼团     待完成
        self.opened3Pin(goodsId)
        self.getpidNow();
      }else{
        //人人拼  无需改动
        self.show_Pin_poeple()// 人人拼 人员列表  已参与
      }
    } else {
      //分享之后  shareYes
      //分享之后 3个头像 显示   将 获取接口 显示出来。

      if (goodsType == 'three') {
        self.opened3Pin(goodsId)
        self.getList_CanT(goodsId)//三人拼 —— 参团列表 - 显示
        //分享之后 3个头像 显示   将 获取接口 显示出来。
        self.getList(pid)//分享之后，此团参团列表  且 判断了该团是否结束
        //分享之后 三人拼
        self.getpidNow();
        self.setData({
          'shareThree': true,
          'type': 'threeC'
        })
      } else {
        //分享之后 人人拼团页面 无需要改
        self.show_Pin_poeple()// 人人拼 人员列表  已参与
      }
    }
  },  
//非主动
  // 设置页面NavigationBarTitle
  setNavTitle(goodsType) {
    if(goodsType != 'people'){
      goodsType = 'three'
    }
    let barTitle = ''
    if (goodsType == 'three') {
      //如果产品是 三人拼 => three
      barTitle = '三人拼'
    }else if(goodsType == 'threeC'){
      //如果产品是 三人拼 => three
      barTitle = '三人拼'
    }else {
      //如果产品是 人人拼 => people
      barTitle = '人人拼'
    }
    wx.setNavigationBarTitle({
      title: barTitle
    })
  },
  //得到产品信息
  getPinInfo(goodsId) {
    let self = this
    wx.request({
      url: util.apiUrl + 'xcx.pin.product',
      data: {
        product: goodsId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success: function (res) {
        console.log(res);
        let error_code = res.data.error_code //错误编码
        let msg = res.data.msg //状态 _ 提示
        //console.log('得到产品信息', res, error_code, msg)//检测数据
        if (error_code == 0) {
          //success
          self.setData({
            'product': res.data.product
          })
        } else if (error_code == 400) {
          //商品已经下架
          wx.showModal({
            title: '提示',
            content: msg,
            success: function (res) {

              if (res.confirm) {
                wx.reLaunch({
                  url: '../index/index'
                })
              } else if (res.cancel) {
                wx.reLaunch({
                  url: '../index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  // 产品详情
  getProductInfo() {
    wx.showLoading({
      title: '加载中...',
    });
    let self = this;
    util.request(util.apiUrl + 'ecapi.product.get', 'POST', {
      product: self.data.id
    }).then(res => {
      // console.log('getProductInfo',res)
      if (res.product.good_stock === 0) {
        util.showToast('商品已经售完', 'error', 1800);
      }
      if (res.product.discount !== null) {
        res.product.discount.end_at = util.formatTime(res.product.discount.end_at);
      }
      if (res.error_code === 0) {
        let CI = res.product.goods_desc;
        res.product.goods_desc = CI.replace(new RegExp('/images/', 'gm'), util.shopUrl + '/images/');
        let specificationList = [];
        if (res.product.properties) {
          specificationList = res.product.properties.map(v => {
            v.checked = false;
            return v;
          });
        }
        let isLiked = true;
        if (res.product.is_liked !== 1) {
          isLiked = false;
        }
        self.setData({
          goods: res.product,
          gallery: res.product.photos,
          specificationList: specificationList,
          productList: res.product.stock,
          userHasCollect: isLiked,
        });
        WxParse.wxParse('goodsDetail', 'html', res.product.goods_desc, self);
      }
      wx.hideLoading();
    });
  },
//非主动 END

//user主动 
  //发起拼团
  pintuan_Send() {
    let type = this.data.type
    if(type != 'people'){
      type = 'three'
    }
    let id = this.data.id
    let pid = this.data.pid
    console.log('发起拼团', type, id, pid)
    wx.navigateTo({
      url: '../confirmOrder/confirmOrder?type=' + type + '&id=' + id + '&pid=' + pid
    })
  },

  indexTo(){
    wx.reLaunch({
      url: '../index/index'
    })
  },

  //拼团已发起 邀请好友
  three_pin_yifa_Fct(){
    let self = this
    let token = wx.getStorageSync('token') || '';
    wx.request({
      url: util.apiUrl + 'xcx.pin.userpindata_pid',
      data: {
        'goods_id': self.data.id
      },
      header: {
        'content-type': 'application/json',
        'X-ECAPI-Authorization': token
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        let pidNow = res.data.pid
        let id = self.data.id
        wx.navigateTo({
          url: '../paymentSuccess/paymentSuccess?type=three&id=' + id + '&pid=' + pidNow + '&modelConsole=' + true
        })
      }
    })
  },

  //参与拼团
  pintuan_Join() {
    let type = this.data.type
    if(type != 'people'){
      type = 'three'
    }
    let id = this.data.id
    let pid = this.data.pid
    //判断 三人拼团  人人拼团
    if (type == 'three'){
      //三人拼团
      //需要接口判断是否为新人，  判断依据是新人就没有参与订单


      let token = wx.getStorageSync('token') || '';
      wx.request({
        url: util.apiUrl + 'xcx.pin.cantuanxianzhi', //仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json', // 默认值
          'X-ECAPI-Authorization': token
        },
        method: 'post',
        success: function (res) {
          if (res.data == true) {
            //true 有数据  老用户  
            wx.showToast({
              title: '您已荣升老客户，请直接发起拼团',
              icon: 'none',
              duration: 1000
            })

            wx.reLaunch({
              url: '../index/index'
            })

          } else {
            //false 没有数据  新用户
            wx.navigateTo({
              url: '../confirmOrder/confirmOrder?type=' + type + '&id=' + id + '&pid=' + pid
            })
          }
        }
      })
    }else{
      //人人拼团
      wx.navigateTo({
        url: '../confirmOrder/confirmOrder?type=' + type + '&id=' + id + '&pid=' + pid
      })
    }
  },

  //查看更多 三人拼团的信息
  moreCha() {
    console.log('moreCha')
    clearInterval(this.data.setInter)
    let self = this
    wx.request({
      url: util.apiUrl + 'xcx.pin.canpintuan',
      data: {
        product: self.data.id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success: function (res) {
        let arr = res.data.cr.reverse()
        console.log(arr)
        self.data.setInter = setInterval(function () {
          let date = new Date();
          let startTime = parseInt(date.getTime() / 1000);
          for (var i = 0; i < arr.length; i++) {
            let time = arr[i].endtime - startTime;
            arr[i].dtime = self.tick(time)
          }
          let arr1 = arr.slice(0, 10)
          self.setData({
            'List_CanT': arr1,
            'tongji': res.data.tongji
          })
        }, 1000)
      }
    })
  },

  //加入拼团，由于列表中 
  comeTuan(event) {
    // console.log(event.currentTarget.dataset.pid);
    let pid = event.currentTarget.dataset.pid; //pid
    let user_name = event.currentTarget.dataset.username; //user_name
    let type = this.data.type
    if(type != 'people'){
      type = 'three'
    }
    let id = this.data.id
    let user = wx.getStorageSync('user')

    //需要调用接口判断是否是新人。  新人就是没有参与过团的人。
    if (user_name == user.nickname){
      wx.showToast({
        title: '亲这是您的团！',
        icon: 'none',
        duration: 2000
      })
    }else{
      let token = wx.getStorageSync('token') || '';
      wx.request({
        url: util.apiUrl + 'xcx.pin.cantuanxianzhi', //仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json', // 默认值
          'X-ECAPI-Authorization':token
        },
        method:'post',
        success: function (res) {
          if(res.data == true){
            //true 有数据  老用户  
            wx.showToast({
              title: '您已荣升老客户，请直接发起拼团',
              icon: 'none',
              duration: 2000
            })
            setTimeout(function(){
              wx.reLaunch({
                url: '../index/index'
              })
            },2000)
          }else{
            //false 没有数据  新用户
            wx.navigateTo({
              url: '../confirmOrder/confirmOrder?type=' + type + '&id=' + id + '&pid=' + pid
            })
          }
        }
      })
    }
  },

//user主动 ~_~ End

//常用函数
  //此函数用于时实计算当前时间
  tick(t) {
    var s = t;  //目标
    var d = s / 86400;  //得到天数
    s %= 86400; //凑不成一天的秒数
    var h = s / 3600; //得到小时
    s %= 3600;  //凑不成一F小时的秒数
    var m = s / 60; //得到分钟
    s %= 60;  //凑不成一分钟的秒数
    // return this.toDou(parseInt(d)) + ':' + this.toDou(parseInt(h)) + ':' + this.toDou(parseInt(m)) + ':' + this.toDou(parseInt(s)); //用字符串拼接的方法替换文本内容
    return this.toDou(parseInt(h)) + ':' + this.toDou(parseInt(m)) + ':' + this.toDou(parseInt(s)); //用字符串拼接的方法替换文本内容
  },

  //补零函数
  toDou(num) {
    return num < 10 ? '0' + num : num;
  },
  //  3人拼，如果自己已经发起拼团不能再次发起拼团
  opened3Pin(goodsId) {
    let token = wx.getStorageSync('token') || '';
    let self = this
    // console.log('opened3Pin——测试',self.data.type,token)
    if (token != '') {
      // console.log('opened3Pin——测试')
      wx.request({
        url: util.apiUrl + 'xcx.pin.userpindata',
        data: {
          'goods_id': goodsId
        },
        header: {
          'content-type': 'application/json',
          'X-ECAPI-Authorization': token
        },
        method: 'POST',
        success: function (res) {
          if (res.data == true) {
            self.setData({
              'three_pin_xiang': false,
              'three_pin_yifa': true
            })
          }
        }
      })
    }
  },
  //分享之后，此团参团列表  且 判断了该团是否结束
  getList(pid) {
    let self = this
    if (pid != 0) {
      wx.request({
        url: util.apiUrl + 'xcx.pin.canpintuan_x',
        data: {
          'pid': pid
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        method: 'POST',
        success: function (res) {
          console.log('getList res', res)
          let arr_cantuan3 = res.data.cantuan //参团数组 
          let cshuliang = res.data.cshuliang  //差多少人数
          if (cshuliang <= 0) {
            //  该团已经结束提示  
            self.setData({
              'three_model': true,
              'type':'three'
            })
            setTimeout(function () {
              self.setData({
                three_model: false
              })
            }, 1000)
          }
          //补齐数组
          for (let i = 0; i < cshuliang; i++) {
            arr_cantuan3.push({ user_id: '', alias: '', user_img: '../../../images/paymentSuccess/jia.png' })
          }
          console.log('getList arr_cantuan3', arr_cantuan3)
          self.setData({
            arr_cantuan3: arr_cantuan3
          })
        }
      })
    }
  },
  //三人拼 —— 参团列表 - 显示
  getList_CanT(goodsId) {
    let self = this
    wx.request({
      url: util.apiUrl + 'xcx.pin.canpintuan',
      data: {
        product: goodsId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success: function (res) {
        let arr = res.data.cr.reverse()
        self.data.setInter = setInterval(function () {
          let date = new Date();
          let startTime = parseInt(date.getTime() / 1000);
          for (var i = 0; i < arr.length; i++) {
            let time = arr[i].endtime - startTime;
            arr[i].dtime = self.tick(time)
          }
          let arr1 = arr.slice(0, 2)
          self.setData({
            'List_CanT': arr1,
            'tongji': res.data.tongji
          })
        }, 1000)
      }
    })
  },
  //人人拼 人员列表  已参与 （仅仅为了展示）   待应用Start
  show_Pin_poeple() {
    let self = this
    let arrJia = [
      {user_img: "http://www.qqzhi.com/uploadpic/2015-01-13/075104244.jpg", alias: "激萌少女", order_status: 10, shipping_status: 0 },
      {user_img: "http://www.qqzhi.com/uploadpic/2015-01-13/055829545.jpg", alias: "青橘酸心", order_status: 10, shipping_status: 0 },
      {user_img: "http://p1.qqyou.com/touxiang/uploadpic/2013-5/10/2013051015595782493.jpg", alias: "发烫的每个吻", order_status: 10, shipping_status: 0 },
      {user_img: "http://pic.qqtn.com/file/2013/2015-5/2015052209124520091.jpg", alias: "想你，我会哭", order_status: 10, shipping_status: 0 },
      {user_img: "http://pic.qqtn.com/up/2017-8/2017082009484846762.jpg", alias: "╰+谁可笑肋谁甾慯悲", order_status: 10, shipping_status: 0 },
      {user_img: "http://b.hiphotos.baidu.com/zhidao/pic/item/4afbfbedab64034f91f0fe0aacc379310a551df8.jpg", alias: "请铭记、那哖の那迗", order_status: 10, shipping_status: 0 },
      {user_img: "http://www.feizl.com/upload2007/2014_06/1406021140162811.jpg", alias: "梦中轻拥", order_status: 10, shipping_status: 0 },
      {user_img: "http://p3.music.126.net/_Sjt9O-ggMTCGzKq5wa5Kg==/3264450032057376.jpg", alias: "↓温гê红唇↑", order_status: 10, shipping_status: 0 },
      {user_img: "http://fd.topitme.com/d/23/ce/1132046888390ce23do.jpg", alias: "埋怨i", order_status: 10, shipping_status: 1 },
    ]
    wx.request({
      url: util.apiUrl + 'xcx.pin.rcanpintuan',
      data: {
        'goods_id': self.data.id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success: function (res) {
          let arr = res.data.data.order
          let Num_mmbhr = res.data.data.shengshuliang
          let arrZhen = arrJia.concat(arr)
          arrZhen = arrZhen.slice(-4, arrZhen.length - 1)
          self.setData({
            'List_mmbhr': arrZhen,
            'Num_mmbhr': Num_mmbhr
          })
      }
    })
  },
//常用函数 END

//生命周期函数--监听页面隐藏
  onHide: function () {
    clearInterval(this.data.setInter)
  },
  onUnload: function () {
    clearInterval(this.data.setInter)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let id = this.data.id
    let user = wx.getStorageSync('user')
    let pid = this.data.pidNow
    let userName = user.nickname

    // console.log(typeof (pid))
    if (res.from === 'button') {
    }
    // 来自页面内转发按钮

    return {
      title: '您的好友(' + userName + ')正在这里买东西，邀请您一起享优惠！',
      path: '/pages/pin_J/pintuan/pintuan?type=three&shareM=shareYes&id=' + id + '&pid=' + pid,
      imageUrl: 'https://www.zhenlvw.com/images/xiao/share2.jpg',
      success: (res) => {
        console.log("转发成功", res);
      },
      fail: (res) => {
        console.log("转发失败", res);
      }
    }
  },
})

